package com.dongdongshop.service.imp;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.*;
import com.dongdongshop.service.AddressService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.IdWorker;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
@org.springframework.stereotype.Service
public class OrderServiceImpl implements OrderService {
    private Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);

    @Reference
    private AddressService addressService;
    @Resource
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Resource
    private TbOrderMapper tbOrderMapper;
    @Resource
    private TbOrderItemMapper tbOrderItemMapper;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public Map<String,Object> getSubmit(TbUser user,Double total) {
        AddressVo add = addressService.getByDefault();
        String s = (String)redisTemplate.opsForValue().get(user.getUsername());
        List<Cart> carlist = JSONObject.parseArray(s,Cart.class);
        /*订单id*/
        String tradeNo = ""+idWorker.nextId();
        for (Cart cart : carlist) {
            Long orderId = idWorker.nextId();
            //创建新订单
            TbOrder tbOrder = new TbOrder();
            //订单id
            tbOrder.setOrderId(orderId);
            //用户名
            tbOrder.setUserId(user.getUsername());
            //支付类型
            tbOrder.setPaymentType("1");
            //状态:1,未付款
            tbOrder.setStatus("1");
            //订单创建日期
            tbOrder.setCreateTime(new Date());
            //订单更新日期
            tbOrder.setUpdateTime(new Date());
            //地址
            tbOrder.setReceiverAreaName(add.getProvinceName()+add.getCityName()+add.getAreaName()+add.getAddress());
            //手机号
            tbOrder.setReceiver(add.getMobile());
            //收货人
            tbOrder.setReceiver(add.getContact());
            //订单来源
            tbOrder.setSourceType("2");
            //商家id
            tbOrder.setSellerId(cart.getSellerId());

            //循环购物车明细
            double money = 0;
            for (TbOrderItem orderItem : cart.getList()) {
                orderItem.setId(idWorker.nextId());
                orderItem.setSellerId(cart.getSellerId());
                money += orderItem.getTotalFee().doubleValue();
                orderItem.setOrderId(orderId);
                orderItem.setStatus("1");
                tbOrderItemMapper.insertSelective(orderItem);
            }
            tbOrder.setTradeNo(tradeNo);
            tbOrder.setPayment(new BigDecimal(money));
            tbOrderMapper.insertSelective(tbOrder);
        }

        /*跳转支付*/
        //订单号
        String WIDout_trade_no = tradeNo;
        //付款金额
        String WIDtotal_amount = total +"";
        //订单名称
        String WIDsubject = "热点商品";
        String WIDbod = "";
        Map<String,Object> map = new HashMap<>();
        map.put("WIDout_trade_no",WIDout_trade_no);
        map.put("WIDtotal_amount",WIDtotal_amount);
        map.put("WIDsubject",WIDsubject);
        map.put("WIDbod",WIDbod);
        //清空购物车中的数据
        redisTemplate.delete(user.getUsername());

        //将购物车信息存储进redis中
        String key = WIDout_trade_no+ user.getUsername();
        redisTemplate.opsForValue().set(key,s);
        return map;
    }

    @Override
    public List<TbOrder> getByTradeNo(String tradeNo) {
        return tbOrderMapper.getByTradeNo(tradeNo);
    }

    @Override
    public void updateStatu(TbOrder tbOrder) {
        tbOrderMapper.updateByPrimaryKey(tbOrder);
    }

    /*关闭订单*/
    @Override
    public void closeOrder(String tradeNo) {
        tbOrderMapper.closeOrder(tradeNo);
    }

    /*查询订单页所有订单*/
    @Override
    public List<OrderItemDTO> getDTO(TbUser user) {
        String username = user.getUsername();
        List<TbOrder> list = tbOrderMapper.getDTO(username);
        List<OrderItemDTO> orderDTOS = new ArrayList<>();
        for (TbOrder tbOrder : list) {
            OrderItemDTO orderDTO = new OrderItemDTO();
            orderDTO.setOrderId(tbOrder.getOrderId());
            orderDTO.setCreateTime(tbOrder.getCreateTime());
            orderDTO.setSellerId(tbOrder.getSellerId());
            orderDTO.setStatus(tbOrder.getStatus());
            //根据orderId查询orderItem详细数据
            List<TbOrderItem> orderItemList = tbOrderItemMapper.selectByOrderId(tbOrder.getOrderId());
            orderDTO.setOrderItem(orderItemList);
            orderDTOS.add(orderDTO);
        }
        return orderDTOS;
    }

    @Override
    public void sendMq(String tradeNo,Double total, String trade_no) {
        List<TbOrder> list = getByTradeNo(tradeNo);
        String userId  = list.get(0).getUserId();
        /*mq发送给积分处理service的参数*/
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("total",total);
        /*本地事物需要的参数*/
        Map<String,Object> map1 = new HashMap<>();
        map1.put("tradeNo",tradeNo);
        map1.put("total",total);
        map1.put("trade_no",trade_no);
        Message message = MessageBuilder.withPayload(map).build();
        logger.info("执行本地事物");
        TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction("down_order", "create_order", message,map1 );
    }
}





























